/**
 * Copyright 2014 wasu.com
 *
 *
 * Create on 2014-12-29 下午3:29:55
 */
package xj.toolkit.jms;

import java.util.Date;

import javax.jms.BytesMessage;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.Session;

import org.apache.commons.collections4.Transformer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;



import com.google.common.base.Preconditions;

/**
 * 发送时候指定发送目的地的消息发送类。
 * 
 * @author <a href="mailto:caoxiaojian@wasu.com>xiaojian.cao</a>
 * 
 */
public class StcMessgeSender {

	private static final Logger logger = LoggerFactory
			.getLogger(StcMessgeSender.class);

	private Transformer<Object, byte[]> transformer;
	private JmsTemplate jmsTemplate;

	/**
	 * @return the decoder
	 */
	public Transformer<Object, byte[]> getTransformer() {
		return transformer;
	}

	/**
	 * @param decoder
	 *            the decoder to set
	 */
	public void setTransformer(Transformer<Object, byte[]> transformer) {
		this.transformer = transformer;
	}

	/**
	 * @return the jmsTemplate
	 */
	public JmsTemplate getJmsTemplate() {
		return jmsTemplate;
	}

	/**
	 * @param jmsTemplate
	 *            the jmsTemplate to set
	 */
	public void setJmsTemplate(JmsTemplate jmsTemplate) {
		this.jmsTemplate = jmsTemplate;
	}

	/**
	 * 发送一条消息到指定的队列（目标）
	 * 
	 * @param targetName
	 *            目标队列或者目标订阅地址名称
	 * @param message
	 *            消息内容
	 */
	public void send(String targetName, Object message) {

		Preconditions.checkArgument(targetName != null
				&& targetName.trim().length() > 0);

		final byte[] content = transformer.transform(message);

		if (content == null || content.length == 0) {
			return;
		}

		jmsTemplate.send(targetName, new MessageCreator() {
			@Override
			public Message createMessage(Session session) throws JMSException {
				BytesMessage bm = session.createBytesMessage();
				bm.setJMSTimestamp(new Date().getTime());
				bm.writeBytes(content);
				return bm;
			}
		});
		
		logger.debug("Send message[" + message + "] to queue[" + targetName + "].");
	}
}
